package com.blog.user.controller;


import com.blog.common.vo.JsonResult;
import com.blog.user.pojo.FileAttachment;
import com.blog.user.service.FileService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName:DownLoadController
 * @Author:wubo
 * @Data:2020/7/28 10:11
 */
@RequestMapping("/api/rest")
@RestController
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("/consumer/downLoad/{id}")
    public ResponseEntity<byte[]> downLoad(@PathVariable String id, HttpServletResponse response) throws IOException {
         FileAttachment fileAttachment = fileService.execute(id);
        HttpHeaders headers = new HttpHeaders();
        String fileName=fileAttachment.getFileName();
        String filePath=fileAttachment.getPath();
        headers.setContentDispositionFormData("attachment",fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filePath)),headers, HttpStatus.OK);
    }

    @RequestMapping("/consumer/upLoad")
    public JsonResult upLoad(MultipartFile file){
        JsonResult rs=fileService.upLoad(file);
        return rs;
    }
}
